package com.heba.fragment.mine;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookAuthorizationException;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.heba.ATApp;
import com.heba.Cfg;
import com.heba.Debug;
import com.heba.dialog.CustomDialogView;
import com.heba.fragment.BaseFragment;
import com.heba.greenmulu.R;
import com.heba.greenmulu.user.UserArticleActivity;
import com.heba.greenmulu.user.UserContributionActivity;
import com.heba.greenmulu.user.UserModifyActivity;
import com.heba.greenmulu.user.UserProductActivity;
import com.heba.greenmulu.user.UserSettingActivity;
import com.heba.helper.MemberShipHelper;
import com.heba.utils.ToastShow;
import com.heba.utils.UniversalImageLoadTool;
import com.tencent.mm.opensdk.modelmsg.SendAuth;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Arrays;

/**
 * 我的界面
 * <p>
 * Created by jason on 2019/2/13.
 */

public class MineFragment extends BaseFragment implements View.OnClickListener {

    private TextView txt_title;
    private ImageView img_back;
    private ImageView img_edit;
    private ImageView img_avatar;
    private TextView txt_nickname;
    private TextView txt_birth;
    private TextView txt_address;
    private TextView txt_articles;
    private TextView txt_products;
    private TextView txt_contribution;
    private TextView txt_email_linked;
    private TextView txt_wechat_linked;
    private TextView txt_facebook_linked;
    private LinearLayout linear_email;
    private LinearLayout linear_wechat;
    private LinearLayout linear_facebook;
    private LinearLayout linear_setting;

    private CallbackManager callbackManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_mine, null);
        callbackManager = CallbackManager.Factory.create();
        initView(view);
        facebookLoginManager();
        return view;
    }

    @Override
    protected void onVisible() {
        super.onVisible();
        getUserInfo();
    }

    @Override
    protected void onHidden() {
        super.onHidden();
    }

    private void initView(View view) {
        txt_title = view.findViewById(R.id.txt_title);
        img_back = view.findViewById(R.id.img_back);
        img_back = view.findViewById(R.id.img_back);
        img_edit = view.findViewById(R.id.img_edit);
        img_avatar = view.findViewById(R.id.img_avatar);
        txt_nickname = view.findViewById(R.id.txt_nickname);
        txt_birth = view.findViewById(R.id.txt_birth);
        txt_address = view.findViewById(R.id.txt_address);
        txt_articles = view.findViewById(R.id.txt_articles);
        txt_products = view.findViewById(R.id.txt_products);
        txt_contribution = view.findViewById(R.id.txt_contribution);
        txt_email_linked = view.findViewById(R.id.txt_email_linked);
        txt_wechat_linked = view.findViewById(R.id.txt_wechat_linked);
        txt_facebook_linked = view.findViewById(R.id.txt_facebook_linked);
        linear_email = view.findViewById(R.id.linear_email);
        linear_wechat = view.findViewById(R.id.linear_wechat);
        linear_facebook = view.findViewById(R.id.linear_facebook);
        linear_setting = view.findViewById(R.id.linear_setting);

        txt_title.setText(getResources().getString(R.string.profile));
        txt_birth.setVisibility(View.GONE);
        img_back.setVisibility(View.INVISIBLE);
        img_edit.setOnClickListener(this);
        txt_articles.setOnClickListener(this);
        txt_products.setOnClickListener(this);
        txt_contribution.setOnClickListener(this);
        linear_email.setOnClickListener(this);
        linear_wechat.setOnClickListener(this);
        linear_facebook.setOnClickListener(this);
        linear_setting.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_edit:
                openActivity(UserModifyActivity.class);
                break;
            case R.id.txt_articles:
                openActivity(UserArticleActivity.class);
                break;
            case R.id.txt_products:
                openActivity(UserProductActivity.class);
                break;
            case R.id.txt_contribution:
                openActivity(UserContributionActivity.class);
                break;
            case R.id.linear_email:
                if (!txt_email_linked.isSelected()) {
                    new CustomDialogView(new CustomDialogView.OnCustomDialogClickListener() {
                        @Override
                        public void onYesClick() {
                            new CustomDialogView(new CustomDialogView.OnCustomBindEmailClickListener() {
                                @Override
                                public void onYesClick(String email) {
                                    new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                                        @Override
                                        public void Success() {
                                            ToastShow.displayToast(getActivity(), getResources().getString(R.string.bind_success));
                                            getUserInfo();
                                        }

                                        @Override
                                        public void Fail(String error) {

                                        }
                                    }).bindEmail(getActivity(), email);
                                }

                                @Override
                                public void onNoClick() {

                                }
                            }).showDialogBindEmail(getActivity());
                        }

                        @Override
                        public void onNoClick() {

                        }
                    }).showDialog(getActivity(), getActivity().getResources().getString(R.string.confirm_bind_email), "");
                }
                break;
            case R.id.linear_wechat:
                if (!txt_wechat_linked.isSelected()) {
                    new CustomDialogView(new CustomDialogView.OnCustomDialogClickListener() {
                        @Override
                        public void onYesClick() {
                            /**
                             * 调起微信授权
                             */
                            if (!ATApp.api.isWXAppInstalled()) {
                                //引导用户去安装微信
                                ToastShow.displayToast(getActivity(), getResources().getString(R.string.wechat_install));
                                Uri uri = Uri.parse("market://details?id=com.tencent.mm");//id为包名
                                Intent it = new Intent(Intent.ACTION_VIEW, uri);
                                startActivity(it);
                                return;
                            }
                            //调起微信授权
                            final SendAuth.Req req = new SendAuth.Req();
                            req.scope = "snsapi_userinfo";
                            req.state = "greenmulu_wx_bind";
                            ATApp.api.sendReq(req);
                        }

                        @Override
                        public void onNoClick() {

                        }
                    }).showDialog(getActivity(), getActivity().getResources().getString(R.string.confirm_bind_wechat), "");
                }
                break;
            case R.id.linear_facebook:
                if (!txt_facebook_linked.isSelected()) {
                    new CustomDialogView(new CustomDialogView.OnCustomDialogClickListener() {
                        @Override
                        public void onYesClick() {
                            LoginManager.getInstance().logInWithReadPermissions(getActivity(), Arrays.asList("public_profile"));
                        }

                        @Override
                        public void onNoClick() {

                        }
                    }).showDialog(getActivity(), getActivity().getResources().getString(R.string.confirm_bind_facebook), "");
                }
                break;
            case R.id.linear_setting:
                openActivity(UserSettingActivity.class);
                break;
            default:
                break;
        }
    }

    /**
     * 获取用户基本信息
     */
    private void getUserInfo() {
        new MemberShipHelper(new MemberShipHelper.MembershipListener() {
            @Override
            public void Success() {
                UniversalImageLoadTool.disPlay(Cfg.Icon, img_avatar, R.drawable.icon_head_portrait);
                txt_nickname.setText(Cfg.NickName + " " + Cfg.LastName);
                if (!Cfg.BirthYear.isEmpty() && !Cfg.BirthMonth.isEmpty()) {
                    String[] months = getResources().getStringArray(R.array.array_month);
                    if (Integer.valueOf(Cfg.BirthMonth) > 0) {
                        txt_birth.setText(months[Integer.valueOf(Cfg.BirthMonth) - 1] + " " + Cfg.BirthYear);
                    }
                }
                txt_address.setText(Cfg.Leng == 0 ? Cfg.Addressen : Cfg.Address);
                if (!Cfg.Email.isEmpty() && !Cfg.Email.equals("null")) {
                    txt_email_linked.setSelected(true);
                    txt_email_linked.setText(getActivity().getResources().getString(R.string.linked));
                } else {
                    txt_email_linked.setSelected(false);
                    txt_email_linked.setText(getActivity().getResources().getString(R.string.not_linked));
                }

                if (!Cfg.Openid.isEmpty() && !Cfg.Openid.equals("null")) {
                    txt_wechat_linked.setSelected(true);
                    txt_wechat_linked.setText(getActivity().getResources().getString(R.string.linked));
                } else {
                    txt_wechat_linked.setSelected(false);
                    txt_wechat_linked.setText(getActivity().getResources().getString(R.string.not_linked));
                }

                if (!Cfg.FaceBookUserID.isEmpty() && !Cfg.FaceBookUserID.equals("null")) {
                    txt_facebook_linked.setSelected(true);
                    txt_facebook_linked.setText(getActivity().getResources().getString(R.string.linked));
                } else {
                    txt_facebook_linked.setSelected(false);
                    txt_facebook_linked.setText(getActivity().getResources().getString(R.string.not_linked));
                }
            }

            @Override
            public void Fail(String error) {
            }
        }).getUserInfo(getActivity());
    }

    /**
     * facebook回调
     */
    private void facebookLoginManager() {
        LoginManager.getInstance().registerCallback(callbackManager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {
                        Debug.Log("facebook success", "loginResult");

                        /**
                         * 获取用户信息
                         */
                        AccessToken token = loginResult.getAccessToken();
                        GraphRequest request = GraphRequest.newMeRequest(token, new GraphRequest.GraphJSONObjectCallback() {
                            @Override
                            public void onCompleted(JSONObject object, GraphResponse response) {
                                Debug.Log("Facebook UserInfo:", response.toString());
                                try {
                                    String id = object.getString("id");

                                    /**
                                     * 发送用户信息至服务器
                                     */
                                    progressDialog.show();
                                    new MemberShipHelper(new MemberShipHelper.MembershipListener() {
                                        @Override
                                        public void Success() {
                                            ToastShow.displayToast(getActivity(), getResources().getString(R.string.bind_success));
                                            getUserInfo();
                                            progressDialog.dismiss();
                                        }

                                        @Override
                                        public void Fail(String error) {
                                            ToastShow.displayToast(getActivity(), getResources().getString(R.string.bind_failure));
                                            progressDialog.dismiss();
                                        }
                                    }).bindFacebook(getActivity(), id);

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                        Bundle parameters = new Bundle();
                        parameters.putString("fields", "id,name,picture");
                        request.setParameters(parameters);
                        request.executeAsync();
                    }

                    @Override
                    public void onCancel() {
                        Debug.Log("facebook cancel", "facebook cancel by user");
                    }

                    @Override
                    public void onError(FacebookException exception) {
                        Debug.Log("facebook error", "exception = " + exception.getMessage());
                        if (exception instanceof FacebookAuthorizationException) {
                            if (AccessToken.getCurrentAccessToken() != null) {
                                LoginManager.getInstance().logOut();
                            }
                        }
                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Debug.Log(this.getClass().getSimpleName(), "onActivityResult");
        callbackManager.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }
}
